<script setup lang='ts'>
import { ref } from 'vue'

//获取bar的dom
let bar = ref<HTMLDivElement>()
//初始化speed为1
let speed = ref<number>(1)
//设置timer来获取动画的id
let timer = ref<number>(0)
const startLoading = () => {
    let dom = bar.value as HTMLDivElement
    console.log("bar-dom:");
    console.log(dom);
    //初始化speed为1，保证速度为1
    speed.value = 1
    timer.value = window.requestAnimationFrame(function fn() {
        //当speed小于90时，speed加1，dom的width设置为speed的值，递归调用实现动画效果
        if (speed.value < 90) {
            speed.value += 1
            dom.style.width = speed.value + '%'
            timer.value = window.requestAnimationFrame(fn)
        } else {
            //重置speed为1
            speed.value = 1
            //取消动画
            window.cancelAnimationFrame(timer.value)
        }
    })
}

//测试效果用
// onMounted(() => {
//     startLoading()
//     endLoading()
// })

const endLoading = () => {
    let dom = bar.value as HTMLDivElement
    setTimeout(() => {
        window.requestAnimationFrame(() => {
            speed.value = 100
            dom.style.width = speed.value + '%'
        })
    }, 200)
}
//把startLoading和endLoading暴露出去
defineExpose({
    startLoading,
    endLoading
})

</script>

<template>
    <div class="wrap">
        <div ref="bar" class="bar"></div>
    </div>
</template>

<style scoped lang='less'>
.wrap {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 2px;

    .bar {
        width: 0;
        height: inherit;
        background-color: skyblue;
    }
}
</style>